const socketIo = require("socket.io");

const gameRooms = {};
let players = [];
let i = 1;
let l = 0;
//创建一个默认房间room1
const createDefaultRoomStatus = () => Array.from({ length: 225 }, () => ({ clicked: false, color: null }));

gameRooms["room1"] = {
	roomStatus: createDefaultRoomStatus(),
	players: [],
	blackAction: true,
	roomName: "官方房间",
	chat: [],
};
//获取所有房间信息，要发送给前端的，优化过的数据
function initRooms() {
	let allRoomsData = [];
	let allRoomsName = Object.keys(gameRooms);
	allRoomsName.forEach((roomId, index) => {
		let roomData = {
			roomId: roomId,
			players: gameRooms[roomId].players,
			roomName: gameRooms[roomId].roomName,
		};
		allRoomsData.push(roomData);
	});
	return allRoomsData;
}
//获取在线玩家信息
function initPlayers() {
	let allPlayersData = [];
	players.forEach((player, index) => {
		let allRoomsName = Object.keys(gameRooms);
		let state = allRoomsName.find((roomId) => gameRooms[roomId].players.some((p) => p.userId === player.userId)) ? "游戏中" : "空闲中";
		allPlayersData.push({ userId: player.userId, userName: player.userName, sid: player.sid, state: state });
	});
	return allPlayersData;
}
function setupSocket(server) {
	const io = socketIo(server, {
		cors: {
			origin: "*",
			methods: ["GET", "POST"],
			credentials: true,
		},
	});

	io.on("connection", (socket) => {
		let allRoomsData = initRooms();
		io.emit("sendRoom", allRoomsData);
		let allPlayersData = initPlayers();
		io.emit("sendPlayer", allPlayersData);
		socket.on("firstConn", (data) => {
			const { userId, sid, userName } = data;

			// 使用find查找现有玩家
			const existingPlayer = players.find((player) => player.userId === userId);

			if (existingPlayer) {
				// 更新现有玩家信息
				existingPlayer.sid = sid;
				existingPlayer.userName = userName;
			} else {
				// 防止重复添加（可选的安全保护）
				if (!players.some((p) => p.userId === userId)) {
					players.push({ userId, sid, userName });
				}
			}

			// console.log(players);
			let allPlayersData = initPlayers();
			io.emit("sendPlayer", allPlayersData);
		});
		socket.on("makeMove", (roomId, index) => {
			let color;
			if (gameRooms[roomId].blackAction) {
				gameRooms[roomId].blackAction = !gameRooms[roomId].blackAction;
				color = "black";
			} else {
				gameRooms[roomId].blackAction = !gameRooms[roomId].blackAction;
				color = "white";
			}
			gameRooms[roomId].roomStatus[index].clicked = true;
			gameRooms[roomId].roomStatus[index].color = color;
			let a = inspection(roomId, index, color);
			if (a.length >= 5) {
				let roomName = gameRooms[roomId].roomName;
				gameRooms[roomId] = {
					roomStatus: createDefaultRoomStatus(),
					players: [],
					blackAction: true,
					roomName: roomName,
					chat: [],
				};
				let allPlayersData = initPlayers();
				io.emit("sendPlayer", allPlayersData);
				io.to(roomId).emit("gameOver", { winner: color, arr: a });
				// allRoomsData = initRooms();
				// io.emit("sendRoom", allRoomsData);
			}
			io.to(roomId).emit("makeMove", { index: index, color: color });
		});

		socket.on("createRoom", (roomName) => {
			i++;
			let roomId = `room${i}`;
			if (gameRooms[roomId]) {
				console.log("房间已存在");
			} else {
				gameRooms[roomId] = {
					roomStatus: createDefaultRoomStatus(),
					players: [],
					blackAction: true,
					roomName: roomName,
					chat: [],
				};
				console.log(`房间${roomId}创建成功`);
				allRoomsData = initRooms();
				io.emit("sendRoom", allRoomsData);
			}
		});
		socket.on("createHideRoom", (data) => {
			l++;
			let roomId = `hide${l}`;
			if (gameRooms[roomId]) {
				console.log("隐藏房间已存在");
			} else {
				gameRooms[roomId] = {
					roomStatus: createDefaultRoomStatus(),
					players: [],
					blackAction: true,
					roomName: "hide",
					chat: [],
					hide: true,
				};
				console.log(`隐藏房间${roomId}创建成功`);
				allRoomsData = initRooms();
				io.emit("sendRoom", allRoomsData);
			}
			let { userId, toUserId } = data;
			let toPlayer = players.find((player) => player.userId === toUserId);
			let tosid = toPlayer.sid;
			let player = players.find((player) => player.userId === userId);
			let sid = player.sid;
			console.log(data);
			io.to(sid).emit("createHideRoom", { roomId });
			io.to(tosid).emit("withPlay", { roomId, userName: player.userName });
		});

		socket.on("joinRoom", (data) => {
			let { roomId, sid, userId } = data;
			if (!gameRooms[roomId]) {
				console.log("房间不存在");
				return;
			}
			// let allRoomsName = Object.keys(gameRooms);
			// allRoomsName.forEach((roomId, index) => {

			// });
			let joinAgain = false;
			gameRooms[roomId].players.forEach((player, index) => {
				if (player.userId === userId) {
					joinAgain = true;
					socket.join(roomId);
					console.log(`用户${userId}又加入了房间${roomId}`);
					let color = index === 0 ? "black" : "white";
					if (!gameRooms[roomId].blackAction) {
						if (color == "black") {
							color = "white";
						} else {
							color = "black";
						}
					}
					if (gameRooms[roomId].players.length == 2) {
						console.log(roomId, gameRooms[roomId].players.length, "房间人数已满，开始游戏");
						io.to(roomId).emit("gameStart");
					}
					let gridStatus = gameRooms[roomId].roomStatus;
					let chat = gameRooms[roomId].chat;
					socket.emit("joinRoom", { roomId, color, gridStatus, chat });
					let allPlayersData = initPlayers();
					io.emit("sendPlayer", allPlayersData);
				}
			});
			if (joinAgain) {
				return;
			}
			if (gameRooms[roomId].players.length >= 2) {
				console.log(`房间${roomId}已满`);
				return;
			}
			gameRooms[roomId].players.push({ userId: userId, sid: sid });
			socket.join(roomId);
			console.log(`用户${userId}加入房间${roomId}`);
			const color = gameRooms[roomId].players.length === 1 ? "black" : "white";
			let gridStatus = gameRooms[roomId].roomStatus;
			let chat = gameRooms[roomId].chat;
			socket.emit("joinRoom", { roomId, color, gridStatus, chat });
			//发送房间信息
			allRoomsData = initRooms();
			io.emit("sendRoom", allRoomsData);
			//发送在线玩家信息
			let allPlayersData = initPlayers();
			io.emit("sendPlayer", allPlayersData);
			if (gameRooms[roomId].players.length == 2) {
				console.log(roomId, gameRooms[roomId].players.length, "房间人数已满，开始游戏");
				io.to(roomId).emit("gameStart");
			}
		});
		socket.on("withPlay", (data) => {});
		socket.on("leaveRoom", (data) => {
			let { roomId, sid } = data;
			if (!gameRooms[roomId]) {
				console.log(roomId, sid);
				console.log("房间不存在");
				return;
			}
			if (!gameRooms[roomId].players.includes(sid)) {
				console.log(`用户${sid}不在房间${roomId}`);
				return;
			}
			gameRooms[roomId].players = gameRooms[roomId].players.filter((player) => player !== sid);
			socket.leave(roomId);
			console.log(`用户${sid}离开房间${roomId}`);
			allRoomsData = initRooms();
			io.emit("sendRoom", allRoomsData);
		});
		socket.on("chat", (data) => {
			let { roomId, userId, msg } = data;
			gameRooms[roomId].chat.push({ userId, msg });
			io.to(roomId).emit("chat", { userId, msg });
		});
		socket.on("disconnect", () => {
			console.log("user disconnected:", socket.id);
			players = players.filter((player) => player.sid !== socket.id);
			let allPlayersData = initPlayers();
			io.emit("sendPlayer", allPlayersData);
		});
	});

	return io;
}

module.exports = setupSocket;
//判断是否成棋
function inspection(roomId, index, color) {
	let roomStatus = gameRooms[roomId].roomStatus;
	let x = index % 15;
	let y = Math.floor(index / 15);
	let a = [];
	console.log(x, y);
	for (let x1 = x - 4; x1 <= x + 4; x1++) {
		if (x1 < 0 || x1 > 14) {
			continue;
		}
		let index1 = 15 * y + x1;
		if (roomStatus[index1].color == color) {
			a.push(index1);
			// console.log(a);
		} else {
			a = [];
		}
		if (a.length >= 5) {
			console.log("成棋");
			return a;
		}
	}
	for (let y1 = y - 4; y1 <= y + 4; y1++) {
		if (y1 < 0 || y1 > 14) {
			continue;
		}
		let index1 = 15 * y1 + x;
		if (roomStatus[index1].color == color) {
			a.push(index1);
		} else {
			a = [];
		}
		if (a.length >= 5) {
			console.log("成棋");
			return a;
		}
	}
	for (let x1 = x - 4, y1 = y - 4; x1 <= x + 4, y1 <= y + 4; x1++, y1++) {
		if (x1 < 0 || x1 > 14 || y1 < 0 || y1 > 14) {
			console.log("超出边界");
			continue;
		}
		let index1 = 15 * y1 + x1;
		if (roomStatus[index1].color == color) {
			a.push(index1);
			console.log("捺", a);
		} else {
			a = [];
		}
		if (a.length >= 5) {
			console.log("成棋");
			return a;
		}
	}
	for (let x1 = x + 4, y1 = y - 4; x1 <= x - 4, y1 <= y + 4; x1--, y1++) {
		if (x1 < 0 || x1 > 14 || y1 < 0 || y1 > 14) {
			console.log("超出边界");
			continue;
		}
		let index1 = 15 * y1 + x1;
		if (roomStatus[index1].color == color) {
			a.push(index1);
			console.log("撇", a);
		} else {
			a = [];
		}
		if (a.length >= 5) {
			console.log("成棋");
			return a;
		}
	}
	return a;
}
